package controller

import (
	adminSrv "book-micro/book-web/pb/admin_pb"
	"book-micro/book-web/utils"
	"context"
	"fmt"
	"github.com/gin-gonic/gin"
)

func Login(ctx *gin.Context) {
	dto := struct {
		Name string `json:"username"`
		Pass string `json:"password"`
	}{}
	_ = ctx.BindJSON(&dto)
	fmt.Println(dto)
	client := adminSrv.NewAdminSrvService("adminsrv", utils.InitMicro().Client())
	resp, err := client.Login(context.TODO(), &adminSrv.LoginRequest{
		Name:     dto.Name,
		Password: dto.Pass,
	})
	if err != nil {
		ctx.JSON(200, gin.H{
			"msg": "服务器开小差了~~",
			"err": err,
		})
		return
	}

	ctx.JSON(200, resp)

}
func Register(ctx *gin.Context) {
	name := ctx.PostForm("username")
	pass := ctx.PostForm("password")
	fmt.Println(name, pass)
	client := adminSrv.NewAdminSrvService("adminsrv", utils.InitMicro().Client())
	resp, err := client.Register(context.TODO(), &adminSrv.LoginRequest{
		Name:     name,
		Password: pass,
	})
	if err != nil {
		ctx.JSON(200, gin.H{
			"msg": "服务器开小差了~~",
		})
		return
	}
	ctx.JSON(200, resp)

}

func ChangePassword(ctx *gin.Context) {
	ch := struct {
		Name string `json:"username"`
		Old  string `json:"old"`
		NewP string `json:"new"`
	}{}
	_ = ctx.BindJSON(&ch)
	fmt.Println(ch)
	client := adminSrv.NewAdminSrvService("adminsrv", utils.InitMicro().Client())
	resp, err := client.ChangePassWord(context.TODO(), &adminSrv.ChangePassWordRequest{
		Name:        ch.Name,
		OldPassword: ch.Old,
		NewPassword: ch.NewP,
	})
	if err != nil {
		ctx.JSON(200, gin.H{
			"msg": "服务器开小差了~~",
		})
		return
	}
	ctx.JSON(200, resp)

}
